<template>
  <view class="alerts-container">
    <!-- 页面头部 -->
    <view class="page-header">
      <view class="header-content">
        <view class="header-title">
          <text class="title">告警管理</text>
          <text class="subtitle">{{deviceInfo.name}} - {{deviceInfo.location}}</text>
        </view>
        <view class="header-stats">
          <view class="stat-item critical">
            <text class="stat-number">{{criticalCount}}</text>
            <text class="stat-label">紧急</text>
          </view>
          <view class="stat-item warning">
            <text class="stat-number">{{warningCount}}</text>
            <text class="stat-label">警告</text>
          </view>
          <view class="stat-item info">
            <text class="stat-number">{{infoCount}}</text>
            <text class="stat-label">提示</text>
          </view>
        </view>
      </view>
    </view>

    <!-- 筛选和搜索 -->
    <view class="filter-section">
      <view class="level-tabs">
        <text
          v-for="tab in levelTabs"
          :key="tab.value"
          class="level-tab"
          :class="{ active: activeLevel === tab.value }"
          @click="activeLevel = tab.value"
        >{{ tab.label }} ({{ tab.count }})</text>
      </view>

      <view class="search-bar">
        <view class="search-input-wrapper">
          <text class="search-icon">🔍</text>
          <input
            v-model="searchKeyword"
            placeholder="搜索告警内容或设备"
            class="search-input"
            @input="handleSearch"
          />
        </view>
        <view class="filter-btn" @click="showFilter = !showFilter">
          <text class="filter-icon">⚙️</text>
          <text>筛选</text>
        </view>
      </view>

      <!-- 高级筛选 -->
      <view v-if="showFilter" class="advanced-filter">
        <view class="filter-row">
          <text class="filter-label">状态：</text>
          <view class="filter-options">
            <text
              v-for="status in statusOptions"
              :key="status.value"
              class="filter-option"
              :class="{ active: filterStatus === status.value }"
              @click="filterStatus = status.value"
            >{{ status.label }}</text>
          </view>
        </view>
        <view class="filter-row">
          <text class="filter-label">时间：</text>
          <view class="filter-options">
            <text
              v-for="time in timeOptions"
              :key="time.value"
              class="filter-option"
              :class="{ active: filterTime === time.value }"
              @click="filterTime = time.value"
            >{{ time.label }}</text>
          </view>
        </view>
      </view>
    </view>

    <!-- 告警列表 -->
    <view class="alert-list">
      <view
        v-for="alert in filteredAlerts"
        :key="alert.id"
        class="alert-card"
        :class="getAlertClass(alert.level)"
        @click="goToDetail(alert.id)"
      >
        <!-- 告警头部 -->
        <view class="alert-header">
          <view class="alert-title-section">
            <text class="alert-title">{{ alert.title }}</text>
            <text class="alert-device">{{ alert.deviceName }}</text>
          </view>
          <view class="alert-level"
                :class="getLevelClass(alert.level)"
          >
            {{ getLevelText(alert.level) }}
          </view>
        </view>

        <!-- 告警内容 -->
        <view class="alert-content">
          <text class="alert-description">{{ alert.description }}</text>
          <view class="alert-location">📍 {{ alert.location }}</view>
        </view>

        <!-- 告警底部 -->
        <view class="alert-footer">
          <view class="alert-time">{{ alert.createTime }}</view>
          <view v-if="alert.status === 'unresolved'" class="alert-status unresolved"
          >
            未处理
          </view>
          <view v-else class="alert-status resolved"
          >
            已处理
          </view>
        </view>
      </view>
    </view>

    <!-- 空状态 -->
    <view v-if="filteredAlerts.length === 0" class="empty-state">
      <text class="empty-icon">🔔</text>
      <text class="empty-title">暂无告警</text>
      <text class="empty-desc">{{ getEmptyDesc() }}</text>
    </view>

    <!-- 刷新按钮 -->
    <view class="refresh-btn" @click="refreshAlerts"
          :class="{ 'refreshing': refreshing }"
    >
      <text class="refresh-icon"
            :class="{ 'rotating': refreshing }"
      >🔄</text>
      <text>{{ refreshing ? '刷新中...' : '刷新' }}</text>
    </view>

    <!-- 自定义底部导航 -->
    <SimpleTabNav :currentTab="3" />
  </view>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
import { onPullDownRefresh } from '@dcloudio/uni-app'
import SimpleTabNav from '@/components/SimpleTabNav.vue'

// 设备信息
const deviceInfo = ref({
  id: '1',
  name: '移动厕所-001',
  location: '人民广场东侧'
})

// 搜索关键词
const searchKeyword = ref('')

// 筛选状态
const activeLevel = ref('all')
const showFilter = ref(false)
const filterStatus = ref('all')
const filterTime = ref('all')

// 刷新状态
const refreshing = ref(false)

// 标签页配置
const levelTabs = ref([
  { label: '全部', value: 'all', count: 0 },
  { label: '紧急', value: 'critical', count: 0 },
  { label: '警告', value: 'warning', count: 0 },
  { label: '提示', value: 'info', count: 0 }
])

// 状态选项
const statusOptions = ref([
  { label: '全部', value: 'all' },
  { label: '未处理', value: 'unresolved' },
  { label: '已处理', value: 'resolved' }
])

// 时间选项
const timeOptions = ref([
  { label: '全部', value: 'all' },
  { label: '今日', value: 'today' },
  { label: '本周', value: 'week' },
  { label: '本月', value: 'month' }
])

// 模拟告警数据
const alerts = ref([
  {
    id: 'AL-20240115001',
    title: '设备离线告警',
    description: '移动厕所-001设备已离线超过30分钟，请立即检查设备状态和网络连接',
    level: 'critical',
    deviceName: '移动厕所-001',
    location: '人民广场东侧',
    status: 'unresolved',
    createTime: '2024-01-15 14:30',
    updateTime: '2024-01-15 14:30'
  },
  {
    id: 'AL-20240115002',
    title: '低电量告警',
    description: '移动厕所-002电池电量低于20%，请及时充电或更换电池',
    level: 'warning',
    deviceName: '移动厕所-002',
    location: '中央公园南门',
    status: 'unresolved',
    createTime: '2024-01-15 13:45',
    updateTime: '2024-01-15 13:45'
  },
  {
    id: 'AL-20240115003',
    title: '温度异常告警',
    description: '移动厕所-003内部温度过高，当前温度32°C，超过设定阈值',
    level: 'warning',
    deviceName: '移动厕所-003',
    location: '商业街北口',
    status: 'resolved',
    createTime: '2024-01-15 12:00',
    updateTime: '2024-01-15 12:30'
  },
  {
    id: 'AL-20240115004',
    title: '清洁度检查提醒',
    description: '移动厕所-004需要进行日常清洁维护',
    level: 'info',
    deviceName: '移动厕所-004',
    location: '体育馆西门',
    status: 'resolved',
    createTime: '2024-01-15 11:00',
    updateTime: '2024-01-15 11:15'
  }
])

// 计算统计
const criticalCount = computed(() => alerts.value.filter(a => a.level === 'critical').length)
const warningCount = computed(() => alerts.value.filter(a => a.level === 'warning').length)
const infoCount = computed(() => alerts.value.filter(a => a.level === 'info').length)

// 更新标签计数
const updateTabCounts = () => {
  levelTabs.value.forEach(tab => {
    if (tab.value === 'all') {
      tab.count = alerts.value.length
    } else {
      tab.count = alerts.value.filter(a => a.level === tab.value).length
    }
  })
}

// 筛选后的告警
const filteredAlerts = computed(() => {
  let result = alerts.value

  // 级别筛选
  if (activeLevel.value !== 'all') {
    result = result.filter(alert => alert.level === activeLevel.value)
  }

  // 状态筛选
  if (filterStatus.value !== 'all') {
    result = result.filter(alert => alert.status === filterStatus.value)
  }

  // 搜索筛选
  if (searchKeyword.value) {
    const keyword = searchKeyword.value.toLowerCase()
    result = result.filter(alert =>
      alert.title.toLowerCase().includes(keyword) ||
      alert.description.toLowerCase().includes(keyword) ||
      alert.deviceName.toLowerCase().includes(keyword) ||
      alert.location.toLowerCase().includes(keyword)
    )
  }

  return result
})

// 获取告警样式类
const getAlertClass = (level: string) => {
  return `alert-${level}`
}

const getLevelClass = (level: string) => {
  return `level-${level}`
}

const getLevelText = (level: string) => {
  const levelMap: Record<string, string> = {
    critical: '紧急',
    warning: '警告',
    info: '提示'
  }
  return levelMap[level] || '未知'
}

// 获取空状态描述
const getEmptyDesc = () => {
  if (searchKeyword.value) {
    return '没有找到匹配的告警，请尝试其他关键词'
  } else if (activeLevel.value !== 'all') {
    return `当前${getLevelText(activeLevel.value)}级别暂无告警`
  } else {
    return '当前暂无告警，系统运行正常'
  }
}

// 跳转到详情
const goToDetail = (id: string) => {
  uni.navigateTo({
    url: `/pages/alerts/detail?id=${id}`
  })
}

// 刷新告警
const refreshAlerts = async () => {
  refreshing.value = true

  // 模拟API调用
  await new Promise(resolve => setTimeout(resolve, 1500))

  // 模拟刷新数据
  const newAlert = {
    id: `AL-${Date.now()}`,
    title: '新告警测试',
    description: '这是一条测试告警信息',
    level: 'info',
    deviceName: '测试设备',
    location: '测试位置',
    status: 'unresolved',
    createTime: new Date().toLocaleString('zh-CN'),
    updateTime: new Date().toLocaleString('zh-CN')
  }

  alerts.value.unshift(newAlert)
  updateTabCounts()
  refreshing.value = false

  uni.showToast({
    title: '刷新成功',
    icon: 'success'
  })
}

// 搜索处理
const handleSearch = () => {
  // 搜索逻辑已通过 computed 自动处理
}

// 下拉刷新
onPullDownRefresh(() => {
  refreshAlerts().then(() => {
    uni.stopPullDownRefresh()
  })
})

// 页面加载
onMounted(() => {
  console.log('告警管理页面加载')
  updateTabCounts()
})

</script>

<style lang="scss" scoped>
.alerts-container {
  min-height: 100vh;
  background: linear-gradient(135deg, #f6ffed 0%, #e6f7ff 100%);
}

// 页面头部
.page-header {
  background: #ffffff;
  padding: 32rpx;
  margin-bottom: 24rpx;
  box-shadow: 0 4rpx 20rpx rgba(0, 0, 0, 0.05);

  .header-content {
    display: flex;
    justify-content: space-between;
    align-items: center;
  }

  .header-title {
    .title {
      display: block;
      font-size: 40rpx;
      font-weight: bold;
      color: #333;
      margin-bottom: 8rpx;
    }

    .subtitle {
      font-size: 26rpx;
      color: #666;
    }
  }

  .header-stats {
    display: flex;
    gap: 32rpx;

    .stat-item {
      text-align: center;
      padding: 16rpx 24rpx;
      border-radius: 16rpx;
      min-width: 120rpx;

      &.critical {
        background: #fff1f0;
        color: #ff4d4f;
      }

      &.warning {
        background: #fff7e6;
        color: #faad14;
      }

      &.info {
        background: #e6f7ff;
        color: #1890ff;
      }

      .stat-number {
        display: block;
        font-size: 32rpx;
        font-weight: bold;
        margin-bottom: 4rpx;
      }

      .stat-label {
        font-size: 24rpx;
      }
    }
  }
}

// 筛选和搜索
.filter-section {
  background: #ffffff;
  padding: 32rpx;
  margin: 0 32rpx 24rpx;
  border-radius: 24rpx;
  box-shadow: 0 4rpx 20rpx rgba(0, 0, 0, 0.05);

  .level-tabs {
    display: flex;
    gap: 16rpx;
    margin-bottom: 24rpx;
    overflow-x: auto;

    .level-tab {
      padding: 16rpx 32rpx;
      background: #f8f9fa;
      border-radius: 24rpx;
      font-size: 28rpx;
      color: #666;
      white-space: nowrap;
      transition: all 0.3s ease;

      &.active {
        background: linear-gradient(135deg, #52c41a, #73d13d);
        color: #ffffff;
        box-shadow: 0 4rpx 12rpx rgba(82, 196, 26, 0.2);
      }
    }
  }

  .search-bar {
    display: flex;
    align-items: center;
    gap: 20rpx;

    .search-input-wrapper {
      flex: 1;
      position: relative;
      display: flex;
      align-items: center;

      .search-icon {
        position: absolute;
        left: 24rpx;
        font-size: 32rpx;
        color: #999;
      }

      .search-input {
        width: 100%;
        height: 80rpx;
        padding: 0 24rpx 0 80rpx;
        border: 2rpx solid #e8e8e8;
        border-radius: 40rpx;
        font-size: 28rpx;
        background: #fafafa;
        transition: all 0.3s ease;

        &:focus {
          border-color: #52c41a;
          background: #ffffff;
          box-shadow: 0 0 0 4rpx rgba(82, 196, 26, 0.1);
        }
      }
    }

    .filter-btn {
      display: flex;
      align-items: center;
      gap: 8rpx;
      padding: 20rpx 24rpx;
      background: linear-gradient(135deg, #52c41a, #73d13d);
      border-radius: 40rpx;
      color: #ffffff;
      font-size: 28rpx;
      font-weight: 500;
      box-shadow: 0 4rpx 12rpx rgba(82, 196, 26, 0.3);

      &:active {
        transform: scale(0.98);
      }
    }
  }

  .advanced-filter {
    margin-top: 24rpx;
    padding: 24rpx;
    background: #f8f9fa;
    border-radius: 16rpx;

    .filter-row {
      display: flex;
      align-items: center;
      margin-bottom: 20rpx;

      &:last-child {
        margin-bottom: 0;
      }

      .filter-label {
        width: 140rpx;
        font-size: 28rpx;
        color: #333;
        font-weight: 500;
      }

      .filter-options {
        flex: 1;
        display: flex;
        gap: 16rpx;
        flex-wrap: wrap;

        .filter-option {
          padding: 12rpx 24rpx;
          background: #ffffff;
          border: 2rpx solid #e8e8e8;
          border-radius: 24rpx;
          font-size: 26rpx;
          color: #666;
          transition: all 0.3s ease;

          &.active {
            background: linear-gradient(135deg, #52c41a, #73d13d);
            color: #ffffff;
            border-color: #52c41a;
            box-shadow: 0 4rpx 12rpx rgba(82, 196, 26, 0.2);
          }
        }
      }
    }
  }
}

// 告警列表
.alert-list {
  padding: 0 32rpx;

  .alert-card {
    background: #ffffff;
    border-radius: 24rpx;
    padding: 32rpx;
    margin-bottom: 24rpx;
    box-shadow: 0 4rpx 20rpx rgba(0, 0, 0, 0.05);
    transition: all 0.3s ease;
    border-left: 8rpx solid transparent;

    &:active {
      transform: scale(0.98);
    }

    &.alert-critical {
      border-left-color: #ff4d4f;
      background: linear-gradient(135deg, #ffffff 0%, #fff1f0 100%);
    }

    &.alert-warning {
      border-left-color: #faad14;
      background: linear-gradient(135deg, #ffffff 0%, #fff7e6 100%);
    }

    &.alert-info {
      border-left-color: #1890ff;
      background: linear-gradient(135deg, #ffffff 0%, #e6f7ff 100%);
    }
  }

  .alert-header {
    display: flex;
    justify-content: space-between;
    align-items: flex-start;
    margin-bottom: 20rpx;

    .alert-title-section {
      flex: 1;

      .alert-title {
        display: block;
        font-size: 32rpx;
        font-weight: bold;
        color: #333;
        margin-bottom: 8rpx;
        line-height: 1.4;
      }

      .alert-device {
        font-size: 26rpx;
        color: #666;
      }
    }

    .alert-level {
      padding: 8rpx 16rpx;
      border-radius: 16rpx;
      font-size: 24rpx;
      font-weight: 500;
      margin-left: 16rpx;

      &.level-critical {
        background: #fff1f0;
        color: #ff4d4f;
      }

      &.level-warning {
        background: #fff7e6;
        color: #faad14;
      }

      &.level-info {
        background: #e6f7ff;
        color: #1890ff;
      }
    }
  }

  .alert-content {
    margin-bottom: 20rpx;

    .alert-description {
      display: block;
      font-size: 28rpx;
      color: #333;
      line-height: 1.6;
      margin-bottom: 12rpx;
    }

    .alert-location {
      font-size: 24rpx;
      color: #666;
      display: flex;
      align-items: center;
      gap: 8rpx;
    }
  }

  .alert-footer {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding-top: 16rpx;
    border-top: 1rpx solid #f0f0f0;

    .alert-time {
      font-size: 24rpx;
      color: #999;
    }

    .alert-status {
      padding: 6rpx 12rpx;
      border-radius: 12rpx;
      font-size: 22rpx;
      font-weight: 500;

      &.unresolved {
        background: #fff1f0;
        color: #ff4d4f;
      }

      &.resolved {
        background: #f6ffed;
        color: #52c41a;
      }
    }
  }
}

// 空状态
.empty-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 120rpx 40rpx;
  text-align: center;

  .empty-icon {
    font-size: 80rpx;
    margin-bottom: 24rpx;
    opacity: 0.5;
  }

  .empty-title {
    font-size: 32rpx;
    color: #666;
    margin-bottom: 16rpx;
    font-weight: 500;
  }

  .empty-desc {
    font-size: 28rpx;
    color: #999;
  }
}

// 刷新按钮
.refresh-btn {
  position: fixed;
  bottom: 40rpx;
  right: 40rpx;
  display: flex;
  align-items: center;
  gap: 12rpx;
  padding: 24rpx 32rpx;
  background: linear-gradient(135deg, #52c41a, #73d13d);
  border-radius: 40rpx;
  color: #ffffff;
  font-size: 28rpx;
  font-weight: 500;
  box-shadow: 0 8rpx 24rpx rgba(82, 196, 26, 0.4);
  transition: all 0.3s ease;

  &.refreshing {
    background: #ccc;
  }

  &:active {
    transform: scale(0.95);
  }

  .refresh-icon {
    font-size: 28rpx;
    transition: transform 0.3s ease;

    &.rotating {
      transform: rotate(360deg);
    }
  }
}
</style>

<style lang="scss">
// 全局样式补充
page {
  background: linear-gradient(135deg, #f6ffed 0%, #e6f7ff 100%);
}
</style>